package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.getTimer;

	/**
	 * 瀑布类，使用水流（falling）作为child
	 *
	 * @author cuilichen
	 */
	public class Waterfall extends Sprite {
		//背景色
		private var bg_color:uint = 0xffffff;
		
		private var char_color:Array; //文字前景色
		private var chars:String;    //文字库，默认是“01”
		private var single:Boolean;  //是否是单字
		private var maxX:int;		 //x方向的最大值
		private var maxY:int;		 //y方向的最大值
		//水平方向上的分布阶数，该数值越大，水平方向上的对象分布约平均
		private var stepNum:int = 10;
		private var fallings:Array; //Falling对象的集合
 
		public function Waterfall(){
			if (stage){
				//init(stage.stageWidth, stage.stageHeight, [0x80ff,0xff0000,0x00ff00], 0, "01", false, 1);
				//init(stage.stageWidth, stage.stageHeight, [0xffffff], 0, "01", false, 1);
				//init(stage.stageWidth, stage.stageHeight, [0xffffff], 0, "ABC");
				//init(stage.stageWidth, stage.stageHeight, [0xffffff], 0, "乾坤");
				init(stage.stageWidth, stage.stageHeight, [0x80ff,0xff0000,0x00ff00], 0, "乾兑震巽坤艮离坎", true, 5);
			}
		}

		/**
		 * 初始化显示设置
		 *
		 * @param        bg_color   背景
		 * @param        char_color 字符颜色
		 * @param        chars		字符
		 */
		public function init(w:int, h:int, char_color:Array, bg_color:uint = 0, chars:String = "01", single:Boolean = false, strengthen:int = 1):void {
			this.bg_color = bg_color;
			this.char_color = char_color;
			this.chars = chars;
			this.fallings = [];
			maxX = w;
			maxY = h;
			
			//背景
			graphics.beginFill(bg_color);
			graphics.drawRect(0, 0, w, h);
			graphics.endFill();
			
			if (chars.charCodeAt(0) > 128){
				Falling.w = 16;
			}
			
			//区域范围
			var inOneStep:int = maxX / stepNum / Falling.w; 
			if (inOneStep < 1){
				inOneStep = 1;
			}
			//inOneStep = 6;
			var count:int = 0;
			for (var i:int = 0; i < inOneStep * strengthen; i++){
				for (var j:int = 0; j < stepNum; j++){     //水平方向上的分布阶数
					createFalling(j, single, "" + count);  //Falling对象
					count++;
				}
			}
			addEventListener(Event.ENTER_FRAME, evt_enter_frame);
		}

		/**
		 * 生成一个Falling对象，并添加到显示队列中
		 *
		 * @param        xMark
		 * @param        single
		 * @param        _name
		 */
		private function createFalling(xMark:int, single:Boolean, _name:String):void {
			var fall:Falling = new Falling(char_color, chars, maxY, single, _name);
			fall.x0 = maxX * (1 / stepNum * xMark + 1 / stepNum * Math.random());
			fall.y = Math.floor(maxY * Math.random() - fall.height);
			fall.cacheAsBitmap = true;
			addChild(fall);
			fallings.push(fall);
		}

		/**
		 * 每帧调用
		 * 对象移动
		 * @param        e
		 */
		private function evt_enter_frame(e:Event):void {
			for (var i:int = 0; i < fallings.length; i++){
				fallings[i].moving();
			}
		}
	}
}